import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import apiUser from '@/api/modules/user'
import { decryptAES, encryptAES } from '@/utils/secret'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref('')
  const companyId = ref('17356608000000001')
  const userInfo = ref({
    id: '',
    username: '',
    nickname: '',
    mobile: '',
    mobile_hidden: '',
    email: '',
    avatar_url: '',
    realname: '',
    gender: '',
    birthday: '',
    idcard_hidden: '',
    has_password_login: '未设置',
    has_password_secure: '未设置',
    user_status: 1,
    user_status_desc: '正常',
    check_status: 0,
    check_status_desc: '未提交',
    bio: '', // 简介
    teaPreference: [], // 喜好
    app_key: '', // 加密
    app_secret: '', // 加密
    access_token: '', // 加密
    expires_in: '',
  })

  const dealerInfo = ref({
    id: '',
    company_id: '',
    shop_name: '',
    shop_type: '',
    v_type: 3, // 资质类型 1-个人 2-个体户 3-企业
    v_type_desc: '',
    shop_logo: '',
    shop_manage: '',
    shop_tel: '',
    platform_type: '',
    currency: '',
    service_config: [],
  })

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && userInfo.value.id && userInfo.value.id !== '')
  const displayName = computed(() => userInfo.value.nickname || userInfo.value.realname || userInfo.value.username || '六堡茶用户')
  const avatarDisplay = computed(() => {
    if (userInfo.value.avatar_url && userInfo.value.avatar_url !== '') {
      return userInfo.value.avatar_url
    }
    return '/static/images/logo.png' // 远程路径
  })

  // 初始化用户数据（从localStorage恢复）
  const initUserData = () => {
    try {
      const saveCompanyId = localStorage.getItem('companyId')
      if (saveCompanyId) {
        companyId.value = saveCompanyId
      }

      const savedUserInfo = localStorage.getItem('userInfo')
      if (savedUserInfo) {
        const parsedUserInfo = JSON.parse(savedUserInfo)

        if (parsedUserInfo && parsedUserInfo.id !== '') {
          const savedToken = parsedUserInfo.access_token

          const now = new Date()
          const expiry = new Date(parsedUserInfo.expires_in)

          if (savedToken && now < expiry) {
            token.value = savedToken
          }

          userInfo.value = { ...userInfo.value, ...parsedUserInfo }
        }
      }
    } catch (error) {
      console.error('初始化用户数据失败:', error)
      // 如果数据损坏，清除localStorage
      localStorage.removeItem('userInfo')
    }
  }

  // 登录
  const login = async (loginData) => {
    try {
      // 这里应该调用实际的登录API
      const res = await apiUser.login(loginData)

      // 保存token和用户信息
      token.value = res.data.access_token
      userInfo.value = { ...userInfo.value, ...res.data }

      // 持久化到localStorage
      localStorage.setItem('token', token.value)
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

      return { success: true, data: res.data }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 注册
  const register = async (registerData) => {
    try {
      // 这里应该调用实际的注册API
      const res = await apiUser.register(registerData)

      // 保存token和用户信息
      token.value = res.data.access_token
      userInfo.value = { ...userInfo.value, ...res.data }

      // 持久化到localStorage
      localStorage.setItem('token', token.value)
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

      return { success: true, data: res.data }
    } catch (error) {
      console.error('注册失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 退出登录
  const logout = () => {
    try {
      // 清除状态
      token.value = ''
      userInfo.value = {
        id: '',
        username: '',
        nickname: '',
        mobile: '',
        mobile_hidden: '',
        email: '',
        avatar_url: '',
        realname: '',
        gender: '',
        birthday: '',
        idcard_hidden: '',
        has_password_login: '未设置',
        has_password_secure: '未设置',
        user_status: 1,
        user_status_desc: '正常',
        check_status: 0,
        check_status_desc: '未提交',
        bio: '', // 简介
        teaPreference: [], // 喜好
        app_key: '',
        app_secret: '',
        access_token: '',
        expires_in: '',
      }

      // 清除localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')

      return { success: true }
    } catch (error) {
      console.error('退出登录失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 更新用户信息
  const updateUserInfo = (newUserInfo) => {
    try {
      userInfo.value = { ...userInfo.value, ...newUserInfo }

      // 更新localStorage
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

      return { success: true }
    } catch (error) {
      console.error('更新用户信息失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 检查登录状态
  const checkLoginStatus = () => {
    return isLoggedIn.value
  }

  // 获取用户信息
  const getUserInfo = async () => {
    if (!isLoggedIn.value) {
      return { success: false, error: '用户未登录' }
    }

    try {
      // 这里应该调用实际的获取用户信息API
      const authId = decryptAES(userInfo.value.app_key)
      const res = await apiUser.getUserInfo({ authId: authId })

      // 保存token和用户信息
      token.value = res.data.access_token
      userInfo.value = { ...userInfo.value, ...res.data }

      // 持久化到localStorage
      localStorage.setItem('token', token.value)
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

      return { success: true, data: userInfo.value }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 更新商家ID信息
  const updateCompanyId = (newCompanyId) => {
    try {
      companyId.value = newCompanyId

      // 更新localStorage
      localStorage.setItem('companyId', newCompanyId)

      return { success: true }
    } catch (error) {
      console.error('更新商家ID失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 获取商家店铺信息
  const getCompanyInfo = async () => {
    try {
      // 这里应该调用实际的获取用户信息API
      const res = await apiUser.getShopInfo()

      // 保存token和用户信息
      companyId.value = res.data.company_id
      dealerInfo.value = { ...dealerInfo.value, ...res.data }

      // 持久化到localStorage
      localStorage.setItem('companyId', companyId.value)
      localStorage.setItem('dealerInfo', JSON.stringify(dealerInfo.value))

      return { success: true, data: dealerInfo.value }
    } catch (error) {
      console.error('获取商家店铺失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 充值方法///////////////////////////////////////////////////////////////////////////////////
  const recharge = async (rechargeData) => {
    try {
      // 这里应该调用实际的充值API
      // const response = await api.recharge(rechargeData)

      // 模拟API响应
      const { amount, paymentMethod } = rechargeData

      // 模拟充值处理时间
      await new Promise((resolve) => setTimeout(resolve, 2000))

      // 更新用户余额
      const currentBalance = parseFloat(userInfo.value.balance || 0)
      const newBalance = currentBalance + parseFloat(amount)

      userInfo.value.balance = newBalance.toFixed(2)

      // 更新localStorage
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

      return {
        success: true,
        data: {
          newBalance: newBalance.toFixed(2),
          amount: parseFloat(amount).toFixed(2),
          paymentMethod,
        },
      }
    } catch (error) {
      console.error('充值失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 获取充值记录
  const getRechargeRecords = async () => {
    try {
      // 这里应该调用实际的API获取充值记录
      // const response = await api.getRechargeRecords()

      // 模拟API响应
      const mockRecords = [
        { id: 1, amount: '100.00', time: '2024-01-15 14:30', status: 'success', paymentMethod: 'alipay' },
        { id: 2, amount: '50.00', time: '2024-01-10 09:15', status: 'success', paymentMethod: 'wechat' },
        { id: 3, amount: '200.00', time: '2024-01-05 16:45', status: 'success', paymentMethod: 'bank' },
      ]

      return { success: true, data: mockRecords }
    } catch (error) {
      console.error('获取充值记录失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 提现方法
  const withdraw = async (withdrawData) => {
    try {
      // 这里应该调用实际的提现API
      // const response = await api.withdraw(withdrawData)

      // 模拟API响应
      const { amount, bankCard, password } = withdrawData

      // 模拟提现处理时间
      await new Promise((resolve) => setTimeout(resolve, 2000))

      // 更新用户余额
      const currentBalance = parseFloat(userInfo.value.balance || 0)
      const newBalance = currentBalance - parseFloat(amount)

      userInfo.value.balance = newBalance.toFixed(2)

      // 更新localStorage
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

      return {
        success: true,
        data: {
          newBalance: newBalance.toFixed(2),
          amount: parseFloat(amount).toFixed(2),
          bankCard,
        },
      }
    } catch (error) {
      console.error('提现失败:', error)
      return { success: false, error: error.message }
    }
  }

  // 获取提现记录
  const getWithdrawRecords = async () => {
    try {
      // 这里应该调用实际的API获取提现记录
      // const response = await api.getWithdrawRecords()

      // 模拟API响应
      const mockRecords = [
        { id: 1, amount: '500.00', time: '2024-01-15 14:30', status: 'success', bankName: '工商银行' },
        { id: 2, amount: '200.00', time: '2024-01-10 09:15', status: 'pending', bankName: '建设银行' },
        { id: 3, amount: '1000.00', time: '2024-01-05 16:45', status: 'success', bankName: '工商银行' },
      ]

      return { success: true, data: mockRecords }
    } catch (error) {
      console.error('获取提现记录失败:', error)
      return { success: false, error: error.message }
    }
  }

  return {
    // 状态
    token,
    companyId,
    userInfo,
    dealerInfo,

    // 计算属性
    isLoggedIn,
    displayName,
    avatarDisplay,

    // 方法
    initUserData,
    login,
    register,
    logout,
    updateUserInfo,
    checkLoginStatus,
    getUserInfo,
    updateCompanyId,
    getCompanyInfo,

    // 业务
    recharge,
    getRechargeRecords,
    withdraw,
    getWithdrawRecords,
  }
})

export default useUserStore
